//
//  ZMyAddressVC.m
//  DistributorAB
//
//  Created by LZY on 2019/10/11.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "ZMyAddressVC.h"
#import "ZMyAddressCell.h"

#import "ZMyAddressModel.h"

#import "ZMyAddressAddVC.h"//添加地址
#import "ZMyAddressDeleteAlertView.h"//删除提示

@interface ZMyAddressVC () <UITableViewDelegate,UITableViewDataSource,ZMyAddressCellDelegate,ZMyAddressDeleteAlertViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *addressArray;
@end

@implementation ZMyAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我的地址";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    [self.rightbutton setImage:imgname(@"address_add_icon") forState:UIControlStateNormal];
    
    _addressArray = [NSMutableArray array];
    
    [self setupViewAction];
    
    [self checkUserAddressList];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkUserAddressList) name:USER_ADD_ADDRESS_SUCCESS object:nil];
}

#pragma mark - 界面布局
- (void)setupViewAction{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviHeight, kScreen_Width, kScreen_Height - kNaviHeight) style:UITableViewStylePlain];
    _tableView.backgroundColor = kColorWithHex(0xf2f2f2);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 150;
    
    [self.view addSubview:_tableView];
    
    //空态界面展示
    _tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:CGRectMake((_tableView.width - 100) / 2.0, (_tableView.height - 72) / 2.0, 100, 72) image:imgname(@"tableviewPlaseholder") viewClick:^{
    }];
    
    [_tableView registerClass:[ZMyAddressCell class] forCellReuseIdentifier:NSStringFromClass([ZMyAddressCell class])];
    
}
#pragma mark - 请求经销商地址列表
- (void)checkUserAddressList{
    kWeakSelf;
    [NetWorkTool POST:checkAddressList param:nil success:^(id dic) {
        NSArray *addressArray = [dic objectForKeyNotNil:@"data"];
        [weakSelf.addressArray removeAllObjects];
        [addressArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ZMyAddressModel *model = [ZMyAddressModel mj_objectWithKeyValues:obj];
            [weakSelf.addressArray addObjectNotNil:model];
        }];
        [weakSelf.tableView reloadData];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _addressArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZMyAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZMyAddressCell class]) forIndexPath:indexPath];
    ZMyAddressModel *model = [_addressArray objectAtIndexSafe:indexPath.row];
    cell.model = model;
    cell.indexPath = indexPath;
    cell.delegate = self;
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZMyAddressModel *model = [_addressArray objectAtIndexSafe:indexPath.row];
    if (self.delegate && [self.delegate respondsToSelector:@selector(addressVCSelectedModel:)]) {
        [self.delegate addressVCSelectedModel:model];
    }
}
#pragma mark - ZMyAddressCellDelegate
- (void)addressCellClickAction:(ZMyAddressCellActionType)actionType indexPath:(NSIndexPath *)indexPath{
    if (actionType == ZMyAddressCellActionTypeDelete) {
        //删除
        ZMyAddressDeleteAlertView *viewAlert = [[ZMyAddressDeleteAlertView alloc] init];
        viewAlert.delegate = self;
        viewAlert.indexPath = indexPath;
        [viewAlert showView];
    }else if (actionType == ZMyAddressCellActionTypeEdit){
        //编辑
        ZMyAddressAddVC *vc = [ZMyAddressAddVC new];
        ZMyAddressModel *model = [self.addressArray objectAtIndexSafe:indexPath.row];
        vc.modelEdit = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)addressDefaultClickActionindexPath:(NSIndexPath *)indexPath
{
    ZMyAddressModel *model = [_addressArray objectAtIndexSafe:indexPath.row];
    if (self.delegate && [self.delegate respondsToSelector:@selector(addressVCSelectedModel:)]) {
        model.is_default = @"1";
        [self.delegate addressVCSelectedModel:model];
    }
}
#pragma mark - ZMyAddressDeleteAlertViewDelegate
- (void)alertViewBtnOkClick:(NSIndexPath *)indexPath{
    [self deleteAddressWithIndex:indexPath];
}
// 删除地址
- (void)deleteAddressWithIndex:(NSIndexPath *)indexPath{
    kWeakSelf;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    ZMyAddressModel *model = [self.addressArray objectAtIndexSafe:indexPath.row];
    if (model) {
        [dict setObjectIfNotNil:model.Id forKey:@"id"];
        [NetWorkTool POST:deleteAgentAddress param:dict success:^(id dic) {
            ShowToastWithText(@"删除地址成功");
            [weakSelf.addressArray removeObjectAtIndex:indexPath.row];
            [weakSelf.tableView reloadData];
            //如果删除的是默认收获地址
            if ([model.is_default isEqualToString:@"1"]) {
                [USER_DEFAULT removeObjectForKey:DEFAULT_ADDRESS];
            }
        } other:^(id dic) {
            ShowToastWithText(dic[@"msg"]);
        } fail:^(NSError *error) {
            
        } needUser:YES];        
    }
    
}
#pragma mark - 交互事件
- (void)rightClick{
    ZMyAddressAddVC *vc = [ZMyAddressAddVC new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
